package com.mrper.ui.main;

import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.miguo.activity.callback.IGoodsScroll;
import com.miguo.activity.callback.listener.GoodsScrollListener;
import com.miguo.app.AppHelper;
import com.miguo.bean.GoodsBean;
import com.miguo.framework.request.FailData;
import com.miguo.framework.request.JsonData;
import com.miguo.framework.utils.Toast;
import com.miguo.framework.view.pulltorefresh.PullToRefreshBase;
import com.miguo.http.HttpClient;
import com.miguo.http.Url;
import com.miguo.ui.R;
import com.miguo.ui.databinding.FragmentHomeListcontentBinding;
import com.miguo.ui.databinding.GriditemGenericGoodsBinding;
import com.mrper.ext.adapter.TempleteAdapter;
import com.mrper.ext.annotation.ContentView;
import com.mrper.ext.uibase.BasicFragment;
import com.mrper.util.AnimationUtil;
import com.mrper.util.DensityUtil;
import com.mrper.util.DeviceUtil;
import com.mrper.util.extra.GoodsUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/22.
 * 首页商品分类展示商品数据
 */
@ContentView(R.layout.fragment_home_listcontent)
public class FragmentHomeListContent extends BasicFragment<FragmentHomeListcontentBinding>
        implements AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListenerTwo<android.widget.GridView>, IGoodsScroll, View.OnClickListener {

    public static final String TAG = FragmentBrandCategoryListContent.class.getSimpleName();
    private TempleteAdapter<GriditemGenericGoodsBinding, GoodsBean> adapter;//数据适配器
    private int currentPage = 0, pageCount = 0, lastVisibleItemIndex = 0;//当前页码,上一次可见的列表项索引
    private long cid = -1;//类型ID

    @Override
    @SuppressWarnings("all")
    protected void initViews() {
        super.initViews();
        cid = getArguments().getLong("cid", 0L);
        dataBinder.setOnClickEvent(this);
        adapter = getGoodsAdapter();
        dataBinder.gvGoods.setAdapter(adapter);
        dataBinder.gvGoods.setNumColumns(2);
        dataBinder.gvGoods.setOnItemClickListener(this);
        dataBinder.gvGoods.setOnRefreshListener(this);
        dataBinder.gvGoods.setOnScrollListener(new GoodsScrollListener(this));
        dataBinder.stateView.setContentView(dataBinder.flCOntainer);
        dataBinder.stateView.getRefreshView().setOnClickListener(this);
        dataBinder.stateView.getNetworkView().setOnClickListener(this);
    }

    @NonNull
    @SuppressWarnings("all")
    private TempleteAdapter<GriditemGenericGoodsBinding, GoodsBean> getGoodsAdapter() {
        return new TempleteAdapter<GriditemGenericGoodsBinding, GoodsBean>(context, R.layout.griditem_generic_goods,
                new TempleteAdapter.OnInitAdapterListener<GriditemGenericGoodsBinding, GoodsBean>() {
                    @Override
                    public void initSetValue(final GriditemGenericGoodsBinding binder, final GoodsBean item, int position) {
                        binder.setGoodsInfo(item);
                        ViewGroup.LayoutParams imglp = binder.imgGoods.getLayoutParams();
                        imglp.height = (int)(DeviceUtil.getScreenWidth(context) - DensityUtil.dip2px(context,21.0f))/2;
                        binder.imgGoods.setLayoutParams(imglp);
                        final boolean isFavor = GoodsUtil.isFavor(context,item);
                        binder.setIsFavor(isFavor);
                        binder.imgFavor.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                GoodsUtil.favorActionWidthImageView(context,binder.imgFavor,item,!isFavor);
                                adapter.notifyDataSetChanged();//刷新数据
                            }
                        });
                    }
                });
    }

    @Override
    protected void doDataLoad() {
        super.doDataLoad();
        loadGoodsData(); //加载商品数据
    }

    @Override
    protected boolean isInitHttpCallback() {
        return false;
    }

    @Override
    public boolean isInitShowLoadingDialog() {
        return true;
    }

    @Override
    public void onScrollIdle() {
        imageLoader.resume();
    }

    @Override
    public void onScrollFling() {
        imageLoader.pause();
    }

    @Override
    public void onScrollTouchScroll() {
        imageLoader.pause();
    }

    @Override
    public void onScrollTopPositiont() {
        // 判断滚动到顶部
        if (dataBinder.img2Top.getVisibility() == View.VISIBLE) {
            dataBinder.img2Top.setVisibility(View.GONE);
            dataBinder.img2Top.startAnimation(AnimationUtil.getGo2TopButton2HideAnimation());
        }
    }

    @Override
    public void onScrollFirstLastPosition() {
        onScrollLastPosition();
//         第一次滚动至底部
        if (dataBinder.img2Top.getVisibility() == View.GONE) {
            dataBinder.img2Top.setVisibility(View.VISIBLE);
            dataBinder.img2Top.startAnimation(AnimationUtil.getGo2TopButton2ShowAnimation());
        }
    }

    @Override
    public void onScrollLastPosition() {
        // 判断滚动到底部
        if (dataBinder.img2Top.getVisibility() == View.GONE) {
            dataBinder.img2Top.setVisibility(View.VISIBLE);
            dataBinder.img2Top.startAnimation(AnimationUtil.getGo2TopButton2ShowAnimation());
        }
        if(currentPage + 1 <= pageCount){
            loadGoodsData();//加载商品数据
        }else {
//            Toast.show(context, "已经到底了!");
            dataBinder.gvGoods.onRefreshComplete();
        }
    }

    @Override
    public void onResume() {
        if (adapter != null)//刷新页面数据
            adapter.notifyDataSetChanged();
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.refresh_rl://刷新事件
            case R.id.network_error_ll://网络错误事件
                loadGoodsData();
                break;
            case R.id.img2Top://去顶部
                dataBinder.gvGoods.setSelection(0);
                onScrollTopPositiont();//执行滚动到顶部隐藏的动画
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        GoodsBean item = (GoodsBean)dataBinder.gvGoods.getItemAtPosition(position);
        AppHelper.startGoodsDetailPage(activity,item);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
        currentPage = 0;
        loadGoodsData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
        if(currentPage + 1>pageCount){
            Toast.show(context, "已经到底了!");
            dataBinder.gvGoods.onRefreshComplete();
            return;
        }
        loadGoodsData();//加载商品数据
    }

    /** 加载商品数据 **/
    private void loadGoodsData(){
        Map<String,String> params = new HashMap<>();
        params.put("cid", String.valueOf(cid));
        params.put("order", cid == 1L?"news":"default");
        params.put("page",String.valueOf(++currentPage));
        HttpClient.post(Url.toRoute(Url.Item.List, 1), params,httpCallback);
    }

    @Override
    public void onLoadHttpDataSuccessful(JsonData json) {
        super.onLoadHttpDataSuccessful(json);
        dataBinder.gvGoods.onRefreshComplete();
        if (json.optInt("status") == 200) {
            JsonData json_data = json.optJson("data");
            try{
                JsonData json_page = json_data.optJson("page");
                pageCount = json_page.optInt("page_size");
                currentPage = json_page.optInt("page");
                if(json_data.has("item")) {
                    List<GoodsBean> mArrayList = new Gson().fromJson(json_data.optJson("item").toString(),
                            new TypeToken<List<GoodsBean>>(){}.getType());
                    if (mArrayList != null && mArrayList.size() > 0) {
                        if(currentPage == 1)
                            adapter.clear();
                        adapter.addItem(mArrayList);
                        adapter.notifyDataSetChanged();
                    }
                    dataBinder.stateView.setRefreshVisibility(View.GONE);
                    return;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            currentPage--;
            Toast.show(context, getResources().getString(R.string.pull_to_refresh_nodata));
        } else {
            currentPage--;
            Toast.show(context, json.optString("info"));
        }
        dataBinder.stateView.setRefreshVisibility(View.VISIBLE);
    }

    @Override
    public void onLoadHttpDataFaield(FailData data) {
        super.onLoadHttpDataFaield(data);
        dataBinder.gvGoods.onRefreshComplete();
        if (currentPage > 0) currentPage--; //页码最小不能小于0，大于0的情况下，如果未加载成功，页面需要还原
        dataBinder.stateView.setRefreshVisibility(View.VISIBLE);
    }

}